<?php

namespace App\Admin\Controllers;

use App\Admin\Extensions\Table\AgentUserSelectTable;
use App\Admin\Extensions\Table\ServiceOrderTable;
use App\Admin\Extensions\Table\UserSelectTable;
use App\Admin\Extensions\Table\WorkerTable;
use App\Admin\Repositories\ShopUser;
use App\Models\BusinessCategory;
use App\Models\User;
use Dcat\Admin\Form;
use Dcat\Admin\Grid;
use Dcat\Admin\Http\Controllers\AdminController;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Illuminate\Validation\Rule;

class ShopController extends AdminController
{

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        return Grid::make(new ShopUser(['user','agent']), function (Grid $grid)  {
            $grid->model()->withCount(['workers','commission as commission_sum'=>function($query){
                $query->select(DB::raw("sum(shop_money) as shopMoney"));
            }])->where("shop_id",0);
            $grid->column('id','门店ID')->sortable();
            $grid->column('agent.name','所属代理商');
            $grid->column('user.nickname','用户昵称');
            $grid->column('name');
            $grid->column('fullname','门店负责人');
            $grid->column('phone','手机号');
            $grid->column('username','门店账号');
            $grid->column('avatar','门店图片')->image(null,40,40);
            $grid->column('address','详细地址')->limit(15);
            $grid->column('money','账号余额');
            $grid->column('workers_count','员工数量')->label()->modal(function (Grid\Displayers\Modal $modal){
                $modal->title("【{$this->name}】员工列表");
                $modal->xl();
                return WorkerTable::make()->payload(['shop_id'=>$this->id]);
            });
            $grid->column('commission_sum','总营业')->display(function ($value){
                return $value?:0.00;
            })->label('success');
            $grid->column('status')->radio(['营业中','暂停营业','已结业'],true)->label(['info','default','danger']);
            $grid->column('created_at');
            $grid->column('view_service','查看洗车订单')->label()->modal(function (Grid\Displayers\Modal $modal){
                $modal->title("【{$this->name}】洗车订单列表");
                $modal->xl();
                return ServiceOrderTable::make()->payload(['shop_id'=>$this->id]);
            });
            $grid->filter(function (Grid\Filter $filter) {
                $filter->panel();
                $filter->expand(false);
                $filter->equal('id')->width(3);
                $filter->like('agent.name','所属代理商')->width(3);
                $filter->like('user.nickname','用户昵称')->width(3);
                $filter->like('shop_user.username','门店账号')->width(3);
                $filter->equal("cid","所属分类")->select(BusinessCategory::getOptions())->width(2);
                $filter->like('name')->width(3);
                $filter->like('fullname','门店负责人')->width(3);
                $filter->like('phone','手机号')->width(3);
                $filter->like('address','详细地址')->width(3);
                $filter->equal("status","状态")->select(['营业中','暂停营业','已结业'])->width(3);
            });
        });
    }


    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        return Form::make(new ShopUser(), function (Form $form) {
            $form->column(5,function (Form $form){
                $form->selectTable('agent_id','所属代理')->title('选择所属代理')
                    ->dialogWidth('60%') // 弹窗宽度，默认 800px
                    ->from(AgentUserSelectTable::make()) // 设置渲染类实例，并传递自定义参数
                    ->model(\App\Models\AgentUser::class, 'id', 'name');
                $form->selectTable('user_id','所属用户')->title('选择用户')
                    ->dialogWidth('60%') // 弹窗宽度，默认 800px
                    ->from(UserSelectTable::make(['id' => $form->getKey(),'is_limit'=>true, 'table' =>'shop_users'])) // 设置渲染类实例，并传递自定义参数
                    ->model(User::class, 'id', 'nickname'); // 设置编辑数据显示
                $form->text('name')->required();
                $form->text('fullname','门店负责人')->required();
                $form->text('phone','手机号')->required();
                $form->title("账号信息");
                $id = $form->getKey();
                $message = ['unique' => '此账号已存在' ];
                $rules = [
                    'required'
                ];
                if($id){
                    $rules[] = Rule::unique('shop_users','username')->ignore($id);
                }else{
                    $rules[] = Rule::unique('shop_users','username');
                }
                $form->text('username','账号')->rules($rules,$message)->required();
                $id = $form->getKey();
                $password = $form->password('password','密码')
                    ->rules(['between:6,15','alpha_num'],['between'=>'请输入6-15为字符','alpha_num'=>'密码必须为大小写字母或者数字'])
                    ->minLength(6,'最少6位字符')
                    ->maxLength(15,'最长15位字符')
                    ->attribute("autocomplete","new-password");
                if($id){
                    $password->help("不修改密码,请留空");
                }else{
                    $password->required();
                }
                $form->image('avatar','门店图片')->uniqueName()->autoUpload()->help("图片尺寸要求:92*70")->required();
//                $form->number('distance','免费接单距离限制(公里)')->default(10);
//                $form->decimal('distance_price','超出距离限制收费(元/公里)')->default(0);
                $form->radio('status')->options(['营业中','暂停营业','已结业'])->default(0);
            });
            $form->column(7,function (Form $form){
                $form->currency('money','账号余额')->symbol("￥")->default(0);
//                $form->rate('rate','每笔交易分配比例')->default(0);
                $form->rate('shop_rate','门店服务每笔交易分成比例')->default(0);
                $form->rate('card_rate','门店洗车卡每笔交易分成比例')->default(0);
                $form->hidden("latitude");
                $form->hidden("longitude");
                $form->tencent_map('latitude', 'longitude','address', '所在地址');
                $form->multipleImage('images','详情轮播图')->uniqueName()->autoUpload()->help("图片尺寸要求:375*218")->required();
            });

            $form->saving(function (Form $form){
                $form->agent_id = $form->agent_id?:0;
                $form->user_id = $form->user_id?:0;
                if($form->isCreating()){
                    $form->password = Hash::make($form->password);
                }
                if ($form->isEditing()){
                    if ($form->password){
                        $form->password = Hash::make($form->password);
                    }else{
                        $form->password = $form->model()->password;
                    }
                }
            });
        });
    }

    /**
     * 自定义地图模型
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\Contracts\View\View
     */
    public function customMap()
    {
        return view('form.tencent');
    }
}
